package aliyun.cx.admin.controller;

import aliyun.cx.admin.entity.Permission;
import aliyun.cx.admin.service.PermissionService;
import aliyun.cx.admin.dto.response.ApiResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 权限管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/admin/permissions")
@RequiredArgsConstructor
public class PermissionController {

    private final PermissionService permissionService;

    /**
     * 获取权限列表（分页）
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('PERM_PERMISSION_MANAGE')")
    public ApiResponse<Page<Permission>> getPermissionList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) String resource) {
        
        try {
            Page<Permission> permissionPage = new Page<>(page, size);
            QueryWrapper<Permission> wrapper = new QueryWrapper<>();
            
            if (name != null && !name.trim().isEmpty()) {
                wrapper.like("name", name.trim());
            }
            if (type != null && !type.trim().isEmpty()) {
                wrapper.eq("type", type.trim());
            }
            if (resource != null && !resource.trim().isEmpty()) {
                wrapper.like("resource", resource.trim());
            }
            
            wrapper.orderByAsc("type", "resource", "action");
            permissionService.page(permissionPage, wrapper);
            
            return ApiResponse.success(permissionPage);
        } catch (Exception e) {
            log.error("获取权限列表失败", e);
            return ApiResponse.error("获取权限列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取权限详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('PERM_PERMISSION_MANAGE')")
    public ApiResponse<Permission> getPermissionById(@PathVariable Long id) {
        try {
            Permission permission = permissionService.getById(id);
            if (permission == null) {
                return ApiResponse.error("权限不存在");
            }
            return ApiResponse.success(permission);
        } catch (Exception e) {
            log.error("获取权限详情失败，ID: {}", id, e);
            return ApiResponse.error("获取权限详情失败: " + e.getMessage());
        }
    }

    /**
     * 创建权限
     */
    @PostMapping("/create")
    @PreAuthorize("hasAuthority('PERM_PERMISSION_MANAGE')")
    public ApiResponse<Permission> createPermission(@RequestBody Permission permission) {
        try {
            // 检查权限名称是否已存在
            if (permissionService.existsByName(permission.getName())) {
                return ApiResponse.error("权限名称已存在");
            }
            
            permission.setCreateTime(LocalDateTime.now());
            permission.setUpdateTime(LocalDateTime.now());
            
            boolean success = permissionService.save(permission);
            if (success) {
                return ApiResponse.success("权限创建成功", permission);
            } else {
                return ApiResponse.error("权限创建失败");
            }
        } catch (Exception e) {
            log.error("创建权限失败", e);
            return ApiResponse.error("创建权限失败: " + e.getMessage());
        }
    }

    /**
     * 更新权限
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('PERM_PERMISSION_MANAGE')")
    public ApiResponse<Permission> updatePermission(@PathVariable Long id, @RequestBody Permission permission) {
        try {
            Permission existingPermission = permissionService.getById(id);
            if (existingPermission == null) {
                return ApiResponse.error("权限不存在");
            }
            
            // 如果权限名称发生变化，检查新名称是否已存在
            if (!existingPermission.getName().equals(permission.getName()) && 
                permissionService.existsByName(permission.getName())) {
                return ApiResponse.error("权限名称已存在");
            }
            
            permission.setId(id);
            permission.setUpdateTime(LocalDateTime.now());
            permission.setCreateTime(existingPermission.getCreateTime()); // 保持原创建时间
            
            boolean success = permissionService.updateById(permission);
            if (success) {
                return ApiResponse.success("权限更新成功", permission);
            } else {
                return ApiResponse.error("权限更新失败");
            }
        } catch (Exception e) {
            log.error("更新权限失败，ID: {}", id, e);
            return ApiResponse.error("更新权限失败: " + e.getMessage());
        }
    }

    /**
     * 删除权限
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('PERM_PERMISSION_MANAGE')")
    public ApiResponse<String> deletePermission(@PathVariable Long id) {
        try {
            Permission permission = permissionService.getById(id);
            if (permission == null) {
                return ApiResponse.error("权限不存在");
            }
            
            boolean success = permissionService.removeById(id);
            if (success) {
                return ApiResponse.success("权限删除成功");
            } else {
                return ApiResponse.error("权限删除失败");
            }
        } catch (Exception e) {
            log.error("删除权限失败，ID: {}", id, e);
            return ApiResponse.error("删除权限失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有权限（不分页，用于角色权限分配）
     */
    @GetMapping("/all")
    @PreAuthorize("hasAuthority('PERM_PERMISSION_MANAGE')")
    public ApiResponse<List<Permission>> getAllPermissions() {
        try {
            QueryWrapper<Permission> wrapper = new QueryWrapper<>();
            wrapper.orderByAsc("type", "resource", "action");
            List<Permission> permissions = permissionService.list(wrapper);
            return ApiResponse.success(permissions);
        } catch (Exception e) {
            log.error("获取所有权限失败", e);
            return ApiResponse.error("获取所有权限失败: " + e.getMessage());
        }
    }

    /**
     * 根据类型获取权限列表
     */
    @GetMapping("/by-type/{type}")
    @PreAuthorize("hasAuthority('PERM_PERMISSION_MANAGE')")
    public ApiResponse<List<Permission>> getPermissionsByType(@PathVariable String type) {
        try {
            List<Permission> permissions = permissionService.getPermissionsByType(type);
            return ApiResponse.success(permissions);
        } catch (Exception e) {
            log.error("根据类型获取权限失败，类型: {}", type, e);
            return ApiResponse.error("获取权限失败: " + e.getMessage());
        }
    }

    /**
     * 根据资源获取权限列表
     */
    @GetMapping("/by-resource/{resource}")
    @PreAuthorize("hasAuthority('PERM_PERMISSION_MANAGE')")
    public ApiResponse<List<Permission>> getPermissionsByResource(@PathVariable String resource) {
        try {
            List<Permission> permissions = permissionService.getPermissionsByResource(resource);
            return ApiResponse.success(permissions);
        } catch (Exception e) {
            log.error("根据资源获取权限失败，资源: {}", resource, e);
            return ApiResponse.error("获取权限失败: " + e.getMessage());
        }
    }

    /**
     * 获取菜单权限
     */
    @GetMapping("/menus")
    @PreAuthorize("hasAuthority('PERM_PERMISSION_MANAGE')")
    public ApiResponse<List<Permission>> getMenuPermissions() {
        try {
            List<Permission> permissions = permissionService.getMenuPermissions();
            return ApiResponse.success(permissions);
        } catch (Exception e) {
            log.error("获取菜单权限失败", e);
            return ApiResponse.error("获取菜单权限失败: " + e.getMessage());
        }
    }

    /**
     * 获取操作权限
     */
    @GetMapping("/actions")
    @PreAuthorize("hasAuthority('PERM_PERMISSION_MANAGE')")
    public ApiResponse<List<Permission>> getActionPermissions() {
        try {
            List<Permission> permissions = permissionService.getActionPermissions();
            return ApiResponse.success(permissions);
        } catch (Exception e) {
            log.error("获取操作权限失败", e);
            return ApiResponse.error("获取操作权限失败: " + e.getMessage());
        }
    }
}